package contactbook.service.impl;

import javax.annotation.EJB;

import javax.ejb.Remote;
import javax.ejb.Stateless;

import contactbook.dao.AccountDAOInterface;
import contactbook.model.Account;
import contactbook.service.AccountServiceInterface;

@Stateless
@Remote(AccountServiceInterface.class)
public class AccountService implements AccountServiceInterface {

	private static final int NULL_ID = -1;
	
	private int ownerId;
	
	@EJB
	private AccountDAOInterface accountDAO;
	
	public AccountService() {
		logout();
	}
	
	@Override
	public Account login(String login, String password) {
		Account ownerAccount = accountDAO.findByLoginPassword(login, password);
		ownerId = (ownerAccount != null) ? ownerAccount.getId() : NULL_ID;
		return ownerAccount; 
	}

	@Override
	public void logout() {
		ownerId = NULL_ID;		
	}

	@Override
	public Account create(Account account) {
		if (!isLogged()) {
			Account a = accountDAO.findByLoginPassword(account.getLogin(), account.getPassword());
			if (a == null) {
				a = accountDAO.create(account);
				ownerId = a.getId();
				return a;
			}
		}
		return null;
	}

	@Override
	public void delete() {
		if (isLogged()) {
			if (accountDAO.findById(ownerId) != null)
				accountDAO.delete(ownerId);
			logout();
		}
	}

	@Override
	public Account getAccountById(int accountId) {
		return accountDAO.findById(accountId);
	}
	
	@Override
	public void update(Account account) {
		if (isLogged())
			accountDAO.update(account);
	}

	@Override
	public void setDAO(AccountDAOInterface dao) {
		this.accountDAO = dao;		
	}
	
	
	@Override
	public boolean isLogged() {
		return ownerId != NULL_ID;
	}
}
